from langchain.agents import AgentExecutor, create_react_agent
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from server.llm_service import DeepSeekFactory
from server.tools import get_chat_history
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.tools import Tool
from langchain.prompts import PromptTemplate
from langchain.agents import create_react_agent, AgentExecutor
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import create_structured_chat_agent, AgentExecutor
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
tools = [
    Tool(
        name="Get_chat_history",
        func=get_chat_history,
        description="明确需要查询聊天记录时才使用,获取两人之间的聊天记录，必要的时候可以总结一下内容。函数的输入格式: \"user_name,target_user_name\"例如: \"yuan,li\""
    )
]
class AgentService:
    _agents = {}

    @classmethod
    def get_agent(cls, info: dict):
        user_id = info['id']
        api_key = info['api']

        if user_id not in cls._agents:
            llm = DeepSeekFactory.get_llm(user_id, api_key)
            prompt = ChatPromptTemplate.from_messages([
                ("system", """你是一个助手，可以使用工具解决问题。规则：
            1. 需要查询聊天记录时使用Get_chat_history工具
            2. 工具返回后整理回答
            3. 不需要工具时直接回答"""),
                MessagesPlaceholder(variable_name="chat_history", optional=True),
                ("human", "{input}"),
                MessagesPlaceholder(variable_name="agent_scratchpad")
            ])

            # 使用 ReAct agent
            agent = create_tool_calling_agent(
                llm=llm,
                tools=tools,
                prompt=prompt
            )

            #创建代理执行器
            agent_executor = AgentExecutor(
                agent=agent,
                tools=tools,
                verbose=True,
                max_iterations=2,
            )

            cls._agents[user_id] = agent_executor

        return cls._agents[user_id]


